package sql;

require 5.004;

use Carp 'croak', 'carp';
use strict;
use warnings;
use DBD::mysql;
use vars qw($VERSION);

$VERSION = 1.0;

sub sql::new {
   my ($class, $db, $host, $user, $pass) = @_;
   my $self = {
      _host => undef,
      _pass => undef,
      _user => undef,
      _db => undef,
      _dbh => undef,
   };

   bless ($self, $class); 
   my $flag = 0;

   if (defined($db)) {
      $self->{_db} = $db;
   }
   else { 
      $flag = 1;
   }

   if (defined($host)) {
      $self->{_host} = $host;
   }
   else { 
      $flag = 1;
   }

   if (defined($user)) {
      $self->{_user} = $user;
   }
   else { 
      $flag = 1;
   }

   if (defined($pass)) {
      $self->{_pass} = $pass;
   }
   else { 
      $flag = 1;
   }

   if ($flag == 0) {
      my $port = 3306;
      my $dsn = "DBI:mysql:database=$self->{_db};host=$self->{_host};port=$port";
      $self->{_dbh} = DBI->connect($dsn, $self->{_user}, $self->{_pass});
   }

   return $self;
}

sub sql::close($)
{
   my ($self) = @_;
   if (defined($self->{_dbh})) {
      $self->{_dbh}->disconnect();
   }
}

sub sql::execute($$)
{
   my (($self), $query) = @_;

   my @retval = ();
   if (defined($self->{_dbh})) {
      my $sth = $self->{_dbh}->prepare($query);
      $sth->execute();
      while (my @rows = $sth->fetchrow_array()) {
         push @retval, \@rows;
      }
      $sth->finish();

   }

   return @retval;
}

sub sql::insert($$)
{
   my (($self), $query) = @_;

   if (defined($self->{_dbh})) {
      if (defined($query)) {
         $self->{_dbh}->do($query);
      }
   }
}

1;
